package com.zzk.lanouhn.myapplication1.fragments;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.adapters.FindAdapter;
import com.zzk.lanouhn.myapplication1.adapters.FindLunBoAdapter;
import com.zzk.lanouhn.myapplication1.modles.FindLunBoModle;
import com.zzk.lanouhn.myapplication1.modles.FindModle;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 发现页面，实际为蝉游记的游记页面
 * Created by lanouhn on 16/8/23.
 */
public class FindFragment extends Fragment {
    private XRecyclerView recyclerView;

    private FindAdapter findAdapter;

    //轮播图设置
    private List<FindLunBoModle> findlunboModle = new ArrayList<>();
    private FindLunBoAdapter lunboAdapter;
    private RollPagerView rollPagerView;

    //上拉刷新和下拉加载
    private int page = 1;
    //最终显示的数据
    private List<FindModle> mList = new ArrayList<>();
    //缓存的数据
    private List<FindModle> tempList = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, null);

        //上拉刷新和下拉加载
        recyclerView = (XRecyclerView) view.findViewById(R.id.find_recyclerView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        //上拉加载风格
        recyclerView.setRefreshProgressStyle(22);
        //下拉刷新动画效果
        recyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //下拉刷新
                page = 1;
                getFindData();
            }

            @Override
            public void onLoadMore() {
                //上拉加载
                page++;
                getFindData();
            }
        });


        rollPagerView = new RollPagerView(getActivity());
        rollPagerView.setPlayDelay(3000);
        rollPagerView.setAnimationDurtion(500);

        LinearLayout.LayoutParams imagebtn_params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, 250);
        rollPagerView.setLayoutParams(imagebtn_params);

        rollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.YELLOW, Color.WHITE));

        recyclerView.addHeaderView(rollPagerView);


//        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
//        recyclerView.setLayoutManager(llm);

        getLnuBoData();
        getFindData();

        return view;
    }

    private void getFindData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String s = Integer.toString(page);
                String url = "http://chanyouji.com/api/trips/featured.json?page=" + s;
                //请求网络
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //网络请求失败
                        handler.sendEmptyMessage(0);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //网络请求成功
                        //解析
                        String result = response.body().string();
                        Gson gson = new Gson();

                        try {
                            JSONArray jsonArray = new JSONArray(result);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                FindModle findModle = gson.fromJson(jsonArray.get(i).toString(), FindModle.class);
                                tempList.add(findModle);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (tempList.size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(2);
                        }
                    }
                });
            }
        }).start();
    }

    private void getLnuBoData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url1 = "http://chanyouji.com/api/adverts.json?name=app_featured_banner_android";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url1).build();

                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(3);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String result = response.body().string();
                        Gson gson = new Gson();

                        try {
                            JSONArray jsonArray = new JSONArray(result);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                FindLunBoModle flbm = gson.fromJson(jsonArray.get(i).toString(), FindLunBoModle.class);
                                findlunboModle.add(flbm);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (findlunboModle.size() > 0) {
                            handler.sendEmptyMessage(4);
                        } else {
                            handler.sendEmptyMessage(5);
                        }

                    }
                });

            }
        }).start();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "失败1", Toast.LENGTH_SHORT).show();
                    recyclerView.refreshComplete();
                    recyclerView.loadMoreComplete();
                    break;
                case 1:
                    if (page == 1) {
                        mList.clear();
                        mList.addAll(tempList);

                        findAdapter = new FindAdapter(getActivity(), mList);
                        recyclerView.setAdapter(findAdapter);

                        recyclerView.refreshComplete();
                        tempList.clear();
                    } else {
                        mList.addAll(tempList);
                        findAdapter.notifyDataSetChanged();
                        recyclerView.loadMoreComplete();
                        tempList.clear();
                    }
                    break;
                case 2:
                    Toast.makeText(getActivity(), "失败2", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(getActivity(), "失败3", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    lunboAdapter = new FindLunBoAdapter(getActivity(), findlunboModle);
                    rollPagerView.setAdapter(lunboAdapter);
                    break;
                case 5:
                    Toast.makeText(getActivity(), "失败5", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

}
